@page "/Admin/Files"
@inject ToastService ToastService
@using BootstrapBlazor.Components
@using System

<PageTitle>文件管理</PageTitle>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <AdminTable2 TItem="FileEntity" Context="item" PageSize="20" Title="文件" DialogClassName="modal-lg"
                         OnQuery="OnQuery" InitQuery="InitQuery" OnRemove="OnRemove" OnEditFinish="OnEditFinish" YesButton="上传至服务器" AddText="上传" IsEdit="false" SkipDbSave="true">

                <TableHeader>
                    <th>文件名</th>
                    <th>文件扩展名</th>
                    <th>文件大小格式化</th>
                    <th>创建者</th>
                    <th>创建时间</th>
                </TableHeader>
                <TableRow>
                    <td><a href="@item.LinkUrl" target="_blank">@item.FileName</a></td>
                    <td>@item.Extension</td>
                    <td>@item.SizeFormat</td>
                    <td>@item.CreatedUserName</td>
                    <td>@item.CreatedTime?.ToString("yyyy-MM-dd HH:mm:ss")</td>
                </TableRow>
                <EditTemplate>
                    <p>选择一个或多个文件后，再点保存。</p>
                    <CardUpload TValue="string" IsMultiple ShowProgress="true" OnChange="@OnCardUpload" OnDelete="@(fileName => Task.FromResult(true))"></CardUpload>
                </EditTemplate>
            </AdminTable2>
        </div>
    </div>
</div>

@code {

    [Inject] IAggregateRootRepository<FileEntity> repo { get; set; }
    [Inject] Services.FileService fileService { get; set; }

    List<UploadFile> uploadFiles { get; set; } = new List<UploadFile>();

    async Task InitQuery(AdminQueryInfo e)
    {
        await Task.Yield();
    }
    void OnQuery(AdminQueryEventArgs<FileEntity> e)
    {
        e.Select.WhereIf(!e.SearchText.IsNull(), a => a.FileName.Contains(e.SearchText) || 
                a.Extension.Contains(e.SearchText) || 
                a.CreatedUserName.Contains(e.SearchText)).OrderByDescending(x=>x.CreatedTime);
    }

    async Task OnCardUpload(UploadFile file)
    {
        if (file != null && file.File != null)
        {
            if (file.IsImage())
            {
                await file.RequestBase64ImageFileAsync("png",200,200);
            }
            uploadFiles.Add(file);
        }
    }

    async Task OnEditFinish(FileEntity entity)
    {
        var total = 0;
        foreach (var file in uploadFiles)
        {
            var result = await fileService.UploadFileAsync(file);
            if (result != null)
            {
                file.PrevUrl = result.LinkUrl;
                total++;
            }
        }

        await ToastService.Success("上传文件", $"已成功上传{total}个文件。");
    }

    async Task OnRemove(AdminRemoveEventArgs<FileEntity> e)
    {
        foreach (var item in e.Items)
        {
            await fileService.DeleteAsync(item.Id);
        }
    }
}
